package com.fenyin.samples.study.jvm.classloader;  

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *@Title:  
 *@Description:  文件类加载器
 *@Author:fengzhichao  
 *@Since:2012-9-21  
 *@Version:1.1.0
 */
public class FileSystemClassLoader extends ClassLoader{
	
	private static final Log log = LogFactory.getLog(FileSystemClassLoader.class);
	
	private String rootDir;
	
	public FileSystemClassLoader(String rootDir){
		this.rootDir = rootDir;
	}
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		byte[] classData = getClassData(name);
		if (classData == null) {
			throw new ClassNotFoundException();
		}else {
			return defineClass(name, classData, 0, classData.length);
		}
	}
	
	private byte[] getClassData(String className){
		String path = classNameToPath(className);
		try {
			InputStream input = new FileInputStream(path);
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			int bufferSize = 4096;
			byte[] buffer = new byte[bufferSize];
			int byteNumRead = 0;
			while((byteNumRead=input.read(buffer))!=-1){
				output.write(buffer, 0, byteNumRead);
			}
			return output.toByteArray();
		} catch (Throwable e) {
			log.error("getClassData error", e);
		}
		return null;
	}
	
	private String classNameToPath(String className){
		return rootDir + File.separatorChar + className.replace('.', File.separatorChar) + ".class";
	}
}
